#include <iostream>
#include <string>
#include <vector>
#include <fstream>

#include <WinSock2.h>
#include <iphlpapi.h>
#include <sstream>
#include <iomanip>
#include <algorithm>


#pragma comment(lib, "iphlpapi.lib")

std::string getMACAddress() {
    PIP_ADAPTER_INFO adapterInfo;
    PIP_ADAPTER_INFO adapter = NULL;
    DWORD bufferSize = sizeof(IP_ADAPTER_INFO);
    adapterInfo = (PIP_ADAPTER_INFO)malloc(bufferSize);

    // 获取适配器信息
    if (GetAdaptersInfo(adapterInfo, &bufferSize) == ERROR_BUFFER_OVERFLOW) {
        free(adapterInfo);
        adapterInfo = (PIP_ADAPTER_INFO)malloc(bufferSize);
    }

    if (GetAdaptersInfo(adapterInfo, &bufferSize) == NO_ERROR) {
        adapter = adapterInfo;
        std::vector<std::string> mac_v;
        // 遍历适配器列表并打印MAC地址
         while (adapter) {
            auto AdapterName = adapter->AdapterName;
            std::stringstream ss;
            for (size_t i = 0; i < adapter->AddressLength; i++) {
                unsigned char macByte = adapter->Address[i];
                if(i != 0){
                    ss<<"-";
                }
                // 两位，不够补0
                ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(macByte);
            }
            std::string mac = ss.str();
            mac_v.emplace_back(mac);
            adapter = adapter->Next;
        }
        return mac_v[0];
    }

    free(adapterInfo);
    return "";
}

std::string GenerateKey(std::string macAddress="")
{
    if(macAddress.empty()){
        macAddress = getMACAddress();
    }
    std::transform(macAddress.begin(), macAddress.end(), macAddress.begin(), [](unsigned char c) { return std::tolower(c); });
    std::hash<std::string> hasher;
    std::size_t hashValue = hasher(macAddress);

    std::ostringstream oss;
    oss << std::hex << std::setw(16) << std::setfill('0') << hashValue * (hashValue/3);

    return oss.str();
}

std::string ReadKey(){
    std::ifstream ifs;
    ifs.open("./key.txt", std::ios::in);
    std::string line;
    if (!ifs.is_open()){
        std::cout << "key.txt file does not exist..." << std::endl;
    }

    if (std::getline(ifs, line)) {
        // 去掉行首的空格
        size_t start = line.find_first_not_of(" \t");
        if (start != std::string::npos) {
            line.erase(0, start);
        }

        // 去掉行尾的空格
        size_t end = line.find_last_not_of(" \t");
        if (end != std::string::npos) {
            line.erase(end + 1);
        }

        // 输出处理后的行
//        std::cout << line << std::endl;
    }

    ifs.close();
    return line;
}

int main(){
//    std::string mac = getMACAddress();
    std::string mac = "FC-34-97-68-55-95";  // 13275dcb02e80f30
    std::string key = GenerateKey(mac);
    std::string txt_key = ReadKey();
//    if(txt_key != key){
//        std::cout<<"Key Error: Please contact the administrator..."<<std::endl;
//        exit(0);
//    }

    std::cout<<key<<std::endl;
}